package com.hugang.socket.udp;

import org.junit.Test;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDPd协议的网络编程
 *
 * @author hg
 * @create 2019 下午 4:34
 */
public class UDPTest {

    /**
     * 发送端
     */
    @Test
    public void sender() throws Exception {
        DatagramSocket datagramSocket = new DatagramSocket();
        DatagramPacket packet = new DatagramPacket("UDP发送数据".getBytes(), 0, "UDP发送数据".getBytes().length, InetAddress.getLocalHost(), 9090);

        int count = 0;
        while (count ++ < 1000) {
            datagramSocket.send(packet);
            Thread.sleep(10);
        }
        datagramSocket.close();


    }

    /**
     * 接收端
     *
     */
    @Test
    public void receiver() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket(9090);
        byte[] bytes = new byte[100];
        DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);
        datagramSocket.receive(datagramPacket);

        System.out.println(new String(datagramPacket.getData(), 0, datagramPacket.getLength()));

        datagramSocket.close();
    }
}
